﻿@using Volo.Abp.Localization
@using System.Globalization
@using System.Collections.Immutable
@inject ILanguageProvider LanguageProvider
@inject IJSRuntime JsRuntime

@if (_otherLanguages != null && _otherLanguages.Any())
{
    <div class="row">
        <label>请选择语言：</label>
        <Dropdown TItem="string" Items="Languages" Size="Size.Small" Color="Color.Info" OnSelectedItemChanged="@ChangeLanguageAsync"></Dropdown>
    </div>
}
@code {
    private IReadOnlyList<LanguageInfo> _otherLanguages;
    private LanguageInfo _currentLanguage;
    private IReadOnlyList<SelectedItem> Languages { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var selectedLanguageName = await JsRuntime.InvokeAsync<string>(
            "localStorage.getItem",
            "Abp.SelectedLanguage"
            );

        _otherLanguages = await LanguageProvider.GetLanguagesAsync();

        if (!_otherLanguages.Any())
        {
            return;
        }

        if (!selectedLanguageName.IsNullOrWhiteSpace())
        {
            _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == selectedLanguageName);
        }

        if (_currentLanguage == null)
        {
            _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == CultureInfo.CurrentUICulture.Name);
        }

        if (_currentLanguage == null)
        {
            _currentLanguage = _otherLanguages.FirstOrDefault();
        }

        Languages = _otherLanguages.Select(I => new SelectedItem { Text = I.DisplayName, Value = I.UiCultureName }).ToImmutableList();
        _otherLanguages = _otherLanguages.Where(l => l != _currentLanguage).ToImmutableList();
    }

    private async Task ChangeLanguageAsync(SelectedItem item)
    {
        var cultureName = item.Value;
        if (cultureName != _currentLanguage.UiCultureName)
        {
            _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == cultureName);
            await JsRuntime.InvokeVoidAsync(
                "localStorage.setItem",
                "Abp.SelectedLanguage", cultureName
                );

            await JsRuntime.InvokeVoidAsync("location.reload");
        }
    }
}
